package com.zuipin.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zuipin.entity.DeliveryAddress;
import com.zuipin.entity.Member;
import com.zuipin.entity.MemberAccount;
import com.zuipin.entity.MemberLevel;
import com.zuipin.enums.MemberStatus;
import com.zuipin.framework.annotation.Inject;
import com.zuipin.framework.annotation.Valid;
import com.zuipin.framework.annotation.Valids;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.service.IDeliveryAddressService;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.service.IMemberLevelService;
import com.zuipin.service.IMemberService;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.Pagination;
import com.zuipin.util.RegexUtils;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.BackMemberDetailVo;
import com.zuipin.vo.BackMemberVo;
import com.zuipin.vo.MemberOrderInfoVo;
import com.zuipin.vo.MemberSearchVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @ClassName: MemberController
 * @author wuyicheng
 * @time 2017年3月23日下午2:27:34
 */
@Api(value = "会员", description = "会员信息-wuyicheng")
@RestController
@RequestMapping(value = "/member")
public class MemberController {
	@Resource
	private IMemberService			memberService;
	@Resource
	private IMemberAccountService	memberAccountService;
	@Resource
	private IMemberLevelService		memberLevelService;
	@Resource
	private IDeliveryAddressService	deliveryAddressService;
	
	private static Logger			log	= LoggerFactory.getLogger(MemberController.class);
	
	@RequestMapping(value = "/searchIsBindingMobilePhone", method = RequestMethod.GET)
	@ApiOperation(value = "判断账号是否绑定手机-wuyicheng", notes = "判断账号是否绑定手机-wuyicheng")
	@Valids({ @Valid(name = "memberId", minValue = 0) })
	@ApiImplicitParams({ @ApiImplicitParam(name = "memberId", value = "会员ID", required = true, dataType = "long", paramType = "query") })
	public Result<Map<String, Object>> searchIsBindingMobilePhone(@RequestParam Long memberId) {
		Result<Map<String, Object>> result = new Result<>();
		Map<String, Object> map = new HashMap<>();
		boolean flag = memberAccountService.isBindingMobilePhone(memberId);
		map.put(ConstantsUtil.RETURN_RESULT, flag);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setData(map);
		return result;
	}
	
	@RequestMapping(value = "/searchMemberByBack", method = RequestMethod.GET)
	@ApiOperation(value = "后台查询会员账户信息-wuyicheng", notes = "后台查询会员账户信息-wuyicheng" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数异常" + "</br>1004-系统异常" + "</br>3006-会员不存在"
			+ "</br>3007-会员帐号不存在" + "</br>4030-输入帐号异常")
	@Valids({ @Valid(name = "inputAccount") })
	@ApiImplicitParams({ @ApiImplicitParam(name = "inputAccount", value = "用户账号", required = true, dataType = "Long", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统ID", required = true, dataType = "Long", paramType = "query") })
	public Result<MemberOrderInfoVo> searchMemberByBack(String inputAccount, Long sysId) {
		Result<MemberOrderInfoVo> result = new Result<>();
		MemberOrderInfoVo memberOrderInfoVo = new MemberOrderInfoVo();
		Member member = memberService.findByLoginName(inputAccount);
		if (member == null && StringUtil.isLong(inputAccount)) {
			Long memberId = Long.valueOf(inputAccount);
			if (memberId != null) {
				member = memberService.findById(memberId);
			}
		}
		if (member != null) {
			MemberAccount memberAccount = memberAccountService.findByMemberIdAndSysId(member.getId(), sysId);
			if (memberAccount != null) {
				if (!MemberStatus.ACTIVE.equals(memberAccount.getStatus())) {
					result.setErrorCode(ErrorCode.MEMBER_IS_FREEZE);
					result.setMessage("会员被禁用");
					return result;
				}
				
				MemberLevel memberLevel = memberLevelService.findById(memberAccount.getMemberLevelId());
				memberOrderInfoVo.setMemberId(member.getId());
				memberOrderInfoVo.setMemberName(inputAccount);
				memberOrderInfoVo.setMemberLevel(memberLevel.getLever());
				memberOrderInfoVo.setMemberLevelName(memberLevel.getMemberLevelName());
				List<DeliveryAddress> list = deliveryAddressService.findList(member.getId(), sysId, null);
				memberOrderInfoVo.setDeliveryAddresseList(list);
				result.setData(memberOrderInfoVo);
				result.setErrorCode(ErrorCode.SUCCESS);
			} else {
				result.setErrorCode(ErrorCode.MEMBER_ACCOUNT_NOT_EXIST);
			}
			
		} else {
			result.setErrorCode(ErrorCode.MEMBER_NOT_EXIST);
		}
		return result;
	}
	
	@RequestMapping(value = "/searchMemberAllByBack", method = RequestMethod.GET)
	@ApiOperation(value = "(后台)查询全部会员信息(可模糊查询)", notes = "(后台)全部查询会员信息(可模糊查询)-zhouhuihang")
	@Valids({ @Valid(name = "sysId", required = true), @Valid(name = "page.pageNumber", required = true), //
			@Valid(name = "page.pageSize", required = true), //
			@Valid(name = "search.beginRegisterTime", regex = RegexUtils.DATE_TIME_FORMAT2), //
			@Valid(name = "search.endRegisterTime", regex = RegexUtils.DATE_TIME_FORMAT2), //
			@Valid(name = "search.beginDisableTime", regex = RegexUtils.DATE_TIME_FORMAT2), //
			@Valid(name = "search.endDisableTime", regex = RegexUtils.DATE_TIME_FORMAT2), //
			@Valid(name = "status", regex = "ACTIVE|FREEZE") })
	@ApiImplicitParams({ @ApiImplicitParam(name = "sysId", value = "系统Id", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "search.phone", value = "绑定手机", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search.memberId", value = "会员编号", required = false, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "search.beginRegisterTime", value = "开始注册日期", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search.endRegisterTime", value = "结束注册日期", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search.beginDisableTime", value = "开始禁用时间", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search.endDisableTime", value = "结束禁用时间", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search.status", value = "'ACTIVE','FREEZE'状态：'已激活','已冻结'", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search.memberLevelIds", value = "等级Id集", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "page.pageNumber", value = "页码", required = true, dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "page.pageSize", value = "单页记录数", required = true, dataType = "integer", paramType = "query"), })
	public Result<List<BackMemberVo>> searchMemberAllByBack(@RequestParam Long sysId, @Inject @ApiIgnore MemberSearchVo search, @Inject @ApiIgnore Pagination page) {
		PageResult<List<BackMemberVo>> result = memberService.searchMemberAllByBack(sysId, search, page);
		return result;
	}
	
	@RequestMapping(value = "/searchMemberByIdBack", method = RequestMethod.GET)
	@ApiOperation(value = "（后台）查询详细会员详情", notes = "（后台）查询详细会员详情-zhouhuihang" + "</br>返回码" + "</br>0-成功" + "</br>2000-没查询到会员")
	@Valids({ @Valid(name = "memberId", required = true), @Valid(name = "sysId", required = true) })
	@ApiImplicitParams({ @ApiImplicitParam(name = "memberId", value = "会员Id", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统Id", required = true, dataType = "long", paramType = "query"), })
	public Result<BackMemberDetailVo> searchMemberByIdBack(@RequestParam Long memberId, @RequestParam Long sysId) {
		Result<BackMemberDetailVo> result = memberService.searchMemberByIdBack(memberId, sysId);
		return result;
	}
	
	@RequestMapping(value = "/modityMemberInformation", method = RequestMethod.POST)
	@ApiOperation(value = "（后台）修改会员信息", notes = "（后台）修改会员信息-zhouhuihang" + "</br>返回码" + "</br>0-成功" + "</br>1002-必填参数为空" + "</br>3008-绑定手机号码已经绑定到另一个帐号" + "</br>3007-用户帐号不存在"
			+ "</br>4034-会员等级不能为空")
	@Valids({ @Valid(name = "backMemberDetailVo.memberId", required = true), //
			@Valid(name = "backMemberDetailVo.memberLevelId", required = true), //
			@Valid(name = "backMemberDetailVo.phone", required = false, regex = RegexUtils.MOBILE_FUZZY), //
			@Valid(name = "backMemberDetailVo.updateId", required = true), //
			@Valid(name = "backMemberDetailVo.email", required = false, regex = RegexUtils.EMAIL), //
			@Valid(name = "backMemberDetailVo.sysId", required = true), //
			@Valid(name = "backMemberDetailVo.nickName", required = false, maxLength = 20), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.id", required = false), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.provinceCode", required = false, regex = RegexUtils.CODE), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.cityCode", required = false, regex = RegexUtils.CODE), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.delFlag", required = false, maxValue = 1, minValue = 0), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.areaCode", required = false, regex = RegexUtils.CODE), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.recName", required = false, maxLength = 20), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.mobilePhone", required = false, regex = RegexUtils.MOBILE_FUZZY), //
			@Valid(name = "backMemberDetailVo.BackDeliveryAddressVo.zipCode", required = false, regex = RegexUtils.CODE) })
	public Result modityMemberInformation(@RequestBody @ApiParam(value = "（后台）修改会员信息") BackMemberDetailVo backMemberDetailVo) throws CustomException {
		Result result = memberService.modityMemberInformation(backMemberDetailVo);
		return result;
	}
	
	@RequestMapping(value = "/modityMemberStatus", method = RequestMethod.POST)
	@ApiOperation(value = "（后台）禁用(已冻结)/启用(已激活) 会员", notes = "（后台）禁用(已冻结)/启用(已激活) 会员-zhouhuihang")
	@Valids({ @Valid(name = "memberId", required = true), @Valid(name = "sysId", required = true), @Valid(name = "status", regex = "ACTIVE|FREEZE") })
	@ApiImplicitParams({ @ApiImplicitParam(name = "memberId", value = "会员Id", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统Id", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "status", value = "'ACTIVE','FREEZE'状态：'已激活','已冻结'", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "updateId", value = "修改人Id", required = true, dataType = "long", paramType = "query") })
	public Result modityMemberStatus(@RequestParam Long memberId, @RequestParam Long sysId, @RequestParam String status, @RequestParam Long updateId) {
		Result result = memberService.modityMemberStatus(memberId, sysId, status, updateId);
		return result;
	}
	
	@RequestMapping(value = "/modifyMemberIntegralOrBalance", method = RequestMethod.POST)
	@ApiOperation(value = "（后台）修改会员积分或者余额", notes = "（后台）修改会员积分或者余额-zhouhuihang")
	@Valids({ @Valid(name = "memberId", required = true), @Valid(name = "sysId", required = true), @Valid(name = "integralOrBalance", regex = "INTEGRAL|BALANCE", required = true),
			@Valid(name = "number", required = true), @Valid(name = "remarks", required = true, maxLength = 500) })
	@ApiImplicitParams({ @ApiImplicitParam(name = "memberId", value = "会员Id", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统Id", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "integralOrBalance", value = "'INTEGRAL','BALANCE'状态：'修改积分'，'修改余额'", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "number", value = "修改积分或余额的数量", required = true, paramType = "query"),
			@ApiImplicitParam(name = "remarks", value = "备注", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "updateId", value = "修改人Id", required = true, dataType = "long", paramType = "query") })
	public Result modifyMemberIntegralOrBalance(@RequestParam Long memberId, @RequestParam Long sysId, @RequestParam String integralOrBalance, @RequestParam BigDecimal number,
			@RequestParam String remarks, @RequestParam Long updateId) throws CustomException {
		Result result = memberService.modifyMemberIntegralOrBalance(memberId, sysId, integralOrBalance, number, remarks, updateId);
		return result;
	}
	
}